<template>
    <div class="m_container">
     
      <!-- 博客内容 -->
      <div class="m_content">
        <el-form ref="editForm" status-icon :model="editForm" :rules="rules1"  label-width="80px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="editForm.title"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="editForm.description"></el-input>
          </el-form-item>
          <el-form-item label="首页图片" prop="first_picture">
            <el-upload
                ref="upload"
                action="/upload"
                name="picture"
                list-type="picture-card"
                :limit="1"
                :file-list="fileList"
                :on-exceed="onExceed"
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-success="handleSuccess"
                :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="this.editForm.first_picture" alt="">
            </el-dialog>
          </el-form-item>

          <el-form-item label="文章标签">
            <!-- <el-input v-model="oldtags" placeholder="请选择标签，多个标签请用逗号隔开" width="80%"></el-input> -->
            <el-tag
              :key="index"
              v-for="(tag,index) in editForm.tags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              style="width: 30%;margin-left: 10px;"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" style="margin-left: 10px;" size="small" @click="showInput">+ New Tag</el-button>
          </el-form-item>

          <el-form-item label="分类专栏" prop="type_id">
            <el-select v-model="editForm.type_id" placeholder="请选择分类专栏" @change="$forceUpdate();">
              <el-option v-for="(item,index) in getalltype" :key="item.index" :label="item.name" :value="item.id + ''"></el-option>
            </el-select>
            <el-button type="primary" size="small" @click="dialog2= true" style="margin-left: 10px;">新建分类专栏</el-button>
          </el-form-item>
          <el-form-item label="文章类型" prop="flag">
            <el-select v-model="editForm.flag" placeholder="请选择文章类型，默认为原创">
              <el-option label="原创" value="原创"></el-option>
              <el-option label="转载" value="转载"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布形式" prop="published">
            <el-select v-model="editForm.published" placeholder="请选择发布形式，默认为私密">
              <el-option label="私密" value="false"></el-option>
              <el-option label="公开" value="true"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="内容" prop="content">
<!--            <mavon-editor v-model="editForm.content"/>-->
            <mavon-editor :ishljs = "true" v-model="editForm.content" ref=md @save="save" @imgAdd="imgAdd" />
          </el-form-item>
          <el-form-item style="margin: auto;">
            <el-button type="primary" @click="submitBlog('editForm')">保存发布</el-button>
            <router-link to="/admin/allblogs">
              <el-button style="margin-left: 10px;">返回</el-button>
            </router-link>
          </el-form-item>

        </el-form>
      </div>
  
  
      <!-- 新建分类专栏 -->
      <el-dialog
        title="新建分类专栏"
        :visible.sync="dialog2"
        width="30%"
        >
        <el-form status-icon :model="type" ref="type" :rules="rules2" label-width="120px">
          <el-form-item label="分类专栏名" prop="name">
            <el-input v-model="type.name" placeholder="请输入要新建的分类专栏名"></el-input>
          </el-form-item>
        </el-form>
         <span slot="footer" class="dialog-footer">
            <el-button @click="dialog2 = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('type')">确 定</el-button>
          </span>
      </el-dialog>
  
  
    </div>
  </template>
  <script>
    export default {
      name: "EditBlog",
      data() {
        //自定义图片上传校验规则
        var checkPictures = (rule, value, callback) => { // 图片验证
          if (!this.hasImg) {
            callback(new Error('请上传图片'));
          } else {
            callback();
          }
        }
        return {
          // id:'',
          editForm: {  //博客文章表单
            // id: null,
            id: '',
            title: '',
            description: '',
            content: '',
            contentHtml:'',
            type_id: '',
            flag: '',
            published: null,
            tags: [],
            first_picture: '',
            shareStatement: null
          },
          oldtags: '',  //字符串类型的标签
          type: {  //分类专栏
            name: ''
          },
          getalltype: [], // 所有分类专栏
          dialogFormVisible: false,  //控制发布博客对话框
          dialog2: false,  //控制新增分类专栏对话框
          rules1: {  //表单校验
            title: [
              {required: true, message: '请输入标题', trigger: 'blur'},
              {min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur'}
            ],
            description: [
              {required: true, message: '请输入摘要', trigger: 'blur'}
            ],
            first_picture: [
              {validator: checkPictures, trigger: 'blur'}
            ],
            content: [
              {required: true, message: '请输入文章内容', trigger: 'blur'}
            ],
            type_id: [
              {required: true, message: '分类专栏不能为空', trigger: 'blur'}
            ],
            flag: [
              {required: true, message: '文章类型不能为空', trigger: 'blur'}
            ],
            published: [
              {required: true, message: '发布形式不能为空', trigger: 'blur'}
            ],
          },
          rules2: { //表单校验
            name: [
              {required: true, message: '分类专栏名不能为空', trigger: 'blur'}
            ],
          },
          formLabelWidth: '120px', // 输入框的宽度
          inputVisible: false,
          inputValue: '',
          btags: null,
          tblogTags: [],
          hasImg: false, //判断是否上传照片

          //  图片上传区
          //文件上传的参数
          dialogVisible: false,
          //图片列表（用于在上传组件中回显图片）
          fileList: [{name: '', url: ''}],

          myConfig: {
            // 编辑器不自动被内容撑高
            autoHeightEnabled: false,
            // 初始容器高度
            initialFrameHeight: 500,
            // 初始容器宽度
            initialFrameWidth: '100%',
            // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
            serverUrl: '//localhost:7070/blog/server',
            // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
            UEDITOR_HOME_URL: '/static/ueditor/'
          },

          name: 'img',
          mdId: 1
        }
      },
      props:['id'],
      mounted() {
        this.initBlog()
        this.initType()
      },
      methods: {

        //保存md到后台
        save(){
          //传递name(文件名),typeId(文件所属类别),value(md文件内容）
          // var result=postMd("555","java",this.value);
          // console.log(result);
          var params = {}
          params.name = this.name
          params.typeId = this.mdId
          params.content = this.editForm.content
          this.postRequest("/blog/saveMd",params).then(res => {
            console.log("11111111111")
            console.log(res)
          })
          // this.dialogFormVisible = false

        },

        //保存图片到后台
        imgAdd(pos, $file){
          var _this = this;
          // 第一步.将图片上传到服务器.
          var formdata = new FormData();
          formdata.append('image', $file);
          console.log("2222222222222")
          this.postRequest('/blog/uploadFile',formdata).then(res => {
            console.log('res:'+res)
            var url = res //取出上传成功后的url
            console.log('pos:'+pos)
            _this.$refs.md.$img2Url(pos, url)
          })

          // uploadFile(formdata).then(resp=> {
          //   var url = resp.data; //取出上传成功后的url
          //   if (resp.status == 200) {
          //     //  将后端返回的url放在md中图片的指定位置
          //     console.log(url)
          //     _this.$refs.md.$img2Url(pos, url)
          //   } else {
          //     _this.$message({type: resp.status, message: resp.statusText});
          //   }
          // });
        },

        //去掉某个标签
        handleClose(tag) {
          this.editForm.tblogTags.splice(this.editForm.tblogTags.indexOf(tag), 1);
        },
        //输入标签名
        showInput() {
          this.inputVisible = true;
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        },
        //确定标签
        handleInputConfirm() {
          let inputValue = this.inputValue;
          if (inputValue) {
            this.editForm.tags.push(inputValue);
          }
          this.inputVisible = false;
          this.inputValue = '';
        },
        //初始化博客数据
        initBlog(){
          const _this = this
          console.log(this.id)
          this.getRequest('/blog/getByBlogId?id=' + this.id).then(resp=>{
            console.log("初始化------------")
            console.log(resp)
            _this.editForm = resp.obj
            //首页图片处理
            _this.editForm.first_picture = resp.obj.firstPicture
            this.fileList[0].name = resp.obj.title+'.jpg'
            this.fileList[0].url = "http://localhost:7070/" + resp.obj.firstPicture + ""
            console.log(this.fileList)
            //发布形式处理
            //发布形式的切换
            _this.editForm.published = resp.obj.published == true ? "公开":"私密"
            // _this.editForm.published = resp.
            //发布形式初始化
            _this.editForm.published = resp.obj.published
            //文章标签处理
            _this.btags = resp.obj.tblogTags
            _this.btags.forEach(element => {
                _this.tblogTags.push(element.ttag.name + '');
            });
            _this.editForm.tags = _this.tblogTags
            //分类专栏初始化
            _this.editForm.type_id = resp.obj.typeId + ''

            // _this.$set(_this.editForm, 'first_picture', resp.obj.firstPicture)
          })
        },
        //初始化文章专栏
        initType(){
          const _this = this
          this.getRequest('/type/getAll').then(resp=>{
            console.log("初始化文章专栏")
            console.log(resp)
            _this.getalltype = resp.obj
            console.log(_this.getalltype)
          })
        },
        //添加新的分类专栏
        addNewType(){
          const _this = this 
          this.postRequest('/type/saveType',this.type).then(resp=>{
            if(resp){
              _this.type.name = ''
              this.initType()
              _this.dialog2 = false
            }
          })
        },
        //校验添加分类专栏表单
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.addNewType()
            } else {
              return false;
            }
          });
        },
        //校验博客基本内容表单
        submitBlog(formName) {
          const _this = this
          this.$refs[formName].validate((valid) => {
            if (valid) {
              //发布博客
                  // alert("更新成功，点击确定跳转到博客列表页面!")

                  // this.$alert('确定要删除文章吗', '删除', {
                  //   confirmButtonText: '确定',
                  //   callback: action => {
                  //     this.$message({
                  //       type: 'success',
                  //       message: '删除成功'
                  //     });
                  //   }
                  // });

                  this.$confirm('确定要保存并发布文章吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {


                    console.log(_this.editForm.published)
                    //将editForm表单中published的数据类型转回boolean类型
                    if(_this.editForm.published == "公开"){
                      _this.$set(_this.editForm, 'published', 'true')
                    }
                    console.log(_this.editForm.published)
                    console.log("============================")
                    // console.log(_this.editForm.shareStatement)
                    if(_this.editForm.shareStatement == true ){
                      _this.$set(_this.editForm, 'shareStatement', "1")
                    }
                    // console.log(_this.editForm.shareStatement)
                    //
                    console.log(_this.editForm)

                    _this.editForm.content = this.$refs.md.d_value
                    _this.editForm.contentHtml = this.$refs.md.d_render
                    // console.log(_this.editForm.content)
                    // console.log(_this.editForm.contentHtml)
                    this.putRequest('/blog/updateBlog',_this.editForm).then(resp=> {
                      console.log("成功执行")
                      if (resp) {
                        this.$message({
                          type: 'success',
                          message: '保存发布成功!'
                        });
                        _this.$router.push('/admin/allblogs')
                      } else {
                        return false
                      }
                    })
                  }).catch((msg) => {
                    this.$message({
                      type: 'info',
                      message: msg
                    });
                  });
                }
              })
        },

        // //阻止upload的自己上传，进行再操作
        // onchange(file,filesList) {
        //   this.hasImg = true;
        //   console.log(file);
        //   //创建临时的路径来展示图片
        //   var windowURL = window.URL || window.webkitURL;
        //   this.src=windowURL.createObjectURL(file.raw);
        //   console.log(file.raw)
        //   console.log("file.name:"+file.name)
        //   //重新写一个表单上传的方法
        //   // this.param = new FormData();
        //   // this.param.append('file', file.raw, file.name);
        //   this.editForm.imgInfo.raw = file.raw
        //   this.editForm.imgInfo.name = file.name
        //   this.editForm.imgInfo.first_picture = file.first_picture
        //   console.log(this.editForm)
        // },
        //
        // //删除上传的图片
        // handleRemove(file,filesList){
        //   // this.param.delete('file')
        //   // console.log(file);
        //   this.hasImg = false;
        //   delete file.raw
        //   delete file.name
        //   this.editForm.imgInfo.raw = file.raw
        //   this.editForm.imgInfo.name = file.name
        //   console.log(this.editForm)
        // },

        //文件上传成功的钩子函数
        handleSuccess(res, file) {
          this.$message({
            type: 'success',
            message: '图片上传成功',
            duration: 6000
          });
          console.log("res:")
          console.log(res)
          console.log("file:")
          console.log(file)
          if (res.code == '0') {
            this.editForm.first_picture = res.data; //将返回的文件储存路径赋值picture字段
            this.hasImg = true
          }
        },
        //删除文件之前的钩子函数
        handleRemove(file, fileList) {
          this.$message({
            type: 'info',
            message: '已删除原有图片',
            duration: 6000
          });
          this.hasImg = false
        },
        //点击列表中已上传的文件事的钩子函数
        handlePreview(file) {
          console.log(file)
        },
        //上传的文件个数超出设定时触发的函数
        onExceed(files, fileList) {
          this.$message({
            type: 'info',
            message: '最多只能上传一个图片',
            duration: 6000
          });
        },
        //文件上传前的前的钩子函数
        //参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
        beforeUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isGIF = file.type === 'image/gif';
          const isPNG = file.type === 'image/png';
          const isBMP = file.type === 'image/bmp';
          const isLt2M = file.size / 1024 / 1024 < 2;

          if (!isJPG && !isGIF && !isPNG && !isBMP) {
            this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 2MB!');
          }
          return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
        },

      }
    }
  </script>
  
  <style>
    .m_container{
      margin-top: 20px;
    }
  </style>
  